package cc.higou.service;

import cc.higou.core.tools.Constants;
import cc.higou.core.tools.FastdfsUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 说明：
 * 上传图片的控制器
 *
 * @author:dongxing
 * @time:--
 */
@Controller
public class UploadFileController {

    private final static Logger LOGGER = LoggerFactory.getLogger(UploadFileController.class);

    /**
     * 上传多图片的控制器
     *
     * @return
     */
    @RequestMapping(value = "/uploadFiles.do")
    @ResponseBody
    public List<String> uploadMultipartFiles(@RequestParam MultipartFile[] mpfs) throws Exception {
        LOGGER.info("开始执行方法");

        List list = new ArrayList();

        for (MultipartFile multipartFile : mpfs) {
            String upload = FastdfsUtil.upload(multipartFile.getBytes(), multipartFile.getOriginalFilename());
            list.add(Constants.FDFS_SERVER + upload);
        }

        return list;

    }


    //富文本编辑器的上传图片（不需要指定文件名）
    @RequestMapping(value = "/uploadFck.do")
    @ResponseBody
    public Map<String, Object> uploadFiles(HttpServletRequest request) throws Exception {

        //强转request
        MultipartRequest mr = (MultipartRequest) request;
        //获得文件
        Map<String, MultipartFile> multipartFileMap = mr.getFileMap();

        Set<Map.Entry<String, MultipartFile>> entrySet = multipartFileMap.entrySet();

        for (Map.Entry<String, MultipartFile> entry : entrySet) {
            //获得文件
            MultipartFile multipartFile = entry.getValue();
            //保存上传的文件
            String upload = FastdfsUtil.upload(multipartFile.getBytes(), multipartFile.getOriginalFilename());
            HashMap<String, Object> map = new HashMap<>();
            //固定格式
            map.put("error", 0);
            map.put("url", Constants.FDFS_SERVER + upload);
            return map;
        }
        return null;

    }
}
